package com.peng.leetcode.other;

/**
 * StringToNum
 *
 * @author: lupeng6
 * @create: 2020/10/16 17:32
 */
public class StringToNum {

    public static void main(String[] args) {
//        System.out.println(new Solution().myAtoi("words and 987"));
//        System.out.println(new Solution().myAtoi("-91283472332"));
//        System.out.println(new Solution().myAtoi("3.14159"));
        System.out.println(new Solution().myAtoi("+-12"));
    }

    static class Solution {
        public int myAtoi(String str) {
            if (str == null || str.length() <= 0) {
                return 0;
            }

            int index = 0;
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c == ' ') {
                    index++;
                    continue;
                } else {
                    break;
                }
            }

            char cs = str.charAt(index);
            if (cs != '-' && cs != '+' && (cs < '0' || cs > '9')) {
                return 0;
            }

            boolean flag = true;
            for (int i = index; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c == '-' || c == '+') {
                    index++;
                    if (c == '-') {
                        flag = false;
                        continue;
                    } else if (c == '+') {
                        flag = true;
                        continue;
                    }
                }
            }

            int num = 0;
            for (int i = index; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c >= '0' && c <= '9') {
                    Integer pop = Integer.valueOf(c + "");
                    if (flag) {
                        int temp = num;
                        if (temp > Integer.MAX_VALUE / 10 || (temp == Integer.MAX_VALUE / 10 && pop > 7)) {
                            return Integer.MAX_VALUE;
                        }
                    } else {
                        int temp = -num;
                        if (temp < Integer.MIN_VALUE / 10 || (temp == Integer.MIN_VALUE / 10 && pop < -8)) {
                            return Integer.MIN_VALUE;
                        }
                    }


                    num = num * 10 + pop;
                } else {
                    break;
                }
            }
            num = flag ? num : -num;
            return num;
        }
    }
}
